<template>
  <div class="change-password-page">
    <div class="page-header">
      <h1>修改密码</h1>
    </div>
    
    <el-card class="password-card">
      <el-form 
        :model="passwordForm" 
        :rules="rules" 
        ref="formRef" 
        label-width="120px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input 
            type="password" 
            v-model="passwordForm.currentPassword" 
            placeholder="请输入当前密码"
            show-password
          ></el-input>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            type="password" 
            v-model="passwordForm.newPassword" 
            placeholder="请输入新密码"
            show-password
          ></el-input>
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            type="password" 
            v-model="passwordForm.confirmPassword" 
            placeholder="请再次输入新密码"
            show-password
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="changePassword" :loading="changing">
            确认修改
          </el-button>
          <el-button @click="resetForm">
            重置
          </el-button>
          <el-button @click="goBack">
            返回
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { changePassword as changePasswordApi } from '@/api/user';
import { ElMessage } from 'element-plus';

export default {
  name: 'ChangePassword',
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    const formRef = ref(null);
    const changing = ref(false);
    
    const passwordForm = ref({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
    
    // 验证新密码确认
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== passwordForm.value.newPassword) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    
    const rules = {
      currentPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, validator: validateConfirmPassword, trigger: 'blur' }
      ]
    };
    
    // 修改密码
    const changePassword = async () => {
      if (!formRef.value) return;
      
      try {
        await formRef.value.validate();
        changing.value = true;
        
        await changePasswordApi({
          currentPassword: passwordForm.value.currentPassword,
          newPassword: passwordForm.value.newPassword
        });
        
        ElMessage.success('密码修改成功，请重新登录');
        
        // 清除用户登录状态
        userStore.logout();
        
        // 跳转到登录页面
        router.push('/login');
      } catch (error) {
        console.error('修改密码失败:', error);
        if (error.response && error.response.status === 400) {
          ElMessage.error('当前密码错误');
        } else {
          ElMessage.error('修改密码失败');
        }
      } finally {
        changing.value = false;
      }
    };
    
    // 重置表单
    const resetForm = () => {
      passwordForm.value = {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    };
    
    const goBack = () => {
      router.go(-1);
    };
    
    return {
      passwordForm,
      rules,
      formRef,
      changing,
      changePassword,
      resetForm,
      goBack
    };
  }
};
</script>

<style scoped>
.change-password-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.password-card {
  max-width: 500px;
  margin: 0 auto;
}

.el-form-item:last-child {
  margin-bottom: 0;
}
</style>